<template>
  <div>
    <van-nav-bar title="注册" left-arrow @click-left="onClickLeft" />
    <van-form colon label-align="right" class="login-box" @submit="onSubmit">
      <van-field
        v-model="username"
        name="username"
        label="账号"
        placeholder="账号"
        :rules="[{ required: true, message: '请填写用户名' }]"
      />
      <van-field
        v-model="password"
        type="password"
        name="password"
        label="密码"
        placeholder="密码"
        :rules="[{ required: true, message: '请填写密码' }]"
      />
      <van-field
        v-model="mobile"
        type="number"
        name="mobile"
        label="手机号"
        placeholder="请输入手机号"
        :rules="[
          { required: true, message: '手机号不能为空' },
          { pattern, message: '请输入格式' },
        ]"
      />
      <van-field
        v-model="code"
        type="number"
        name="code"
        label="验证码"
        placeholder="请输入验证码"
        :rules="[{ required: true, message: '请填写验证码' }]"
      />
      <div style="margin: 20px 50px">
        <van-button round block type="info" native-type="submit"
          >立即注册</van-button
        >
      </div>
    </van-form>
    <div class="register-link" @click="changeLogin">已有账号？立即登录！</div>
  </div>
</template>

<script>
import { NavBar, Field, Form, Button,Notify } from "vant";

import { startRegister } from "@/network/index.js";

export default {
  name: "Login",
  data() {
    return {
      username: "",
      password: "",
      mobile: "",
      code: "",
      pattern: /^[1][356789][0-9]{9}$/,
    };
  },
  components: {
    [NavBar.name]: NavBar,
    [Field.name]: Field,
    [Button.name]: Button,
    [Form.name]: Form,
    [Notify.name]: Notify,
  },
  methods: {
    onClickLeft() { //返回首页
      this.$router.replace("/Home");
    },
    async onSubmit(values) { 
      const info = {  //保存表单信息
        code: this.code,
        mobile: this.mobile,
        password: this.password,
        username: this.username,
      };
      const {data} = await startRegister(info) //开始提交
      //判断
      if(data.errno === 704) {
        Notify({ type: 'danger', message: '该账号已注册' });
      }else if(data.errno === 705) {
        Notify({ type: 'danger', message: '手机号已注册' });
      }else if(data.errno === 0) {
        //如果为0表示注册成功提交用户信息进vuex
        Notify({ type: 'success', message: '注册成功' });

        this.$store.commit('setUserInfo',data.data)
        //跳转进个人中心页
        this.$router.push({name:'Profile'})
      }
    },
    changeLogin() {
      this.$router.replace("/Login");
    },
  },
  created() {},
  mounted() {},
};
</script>

<style lang="less" scoped>
.van-field--label-right {
  margin: 20px auto;
}
.login-box {
  margin-top: 100px;
  // margin: 30px auto;
}
.register-link {
  font-size: 14px;
  color: gray;
  margin: 0 50px;
  text-align: right;
}
</style>

